home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9358 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: lrz-muenchen.de!news
  2. From: watzka@stat.uni-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Crash Proofing?
  5. Date: 9 Mar 1996 19:27:07 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4hsm2b$3qd@sparcserver.lrz-muenchen.de>
  9. References: <4hsfje$rbr@uwm.edu>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. peterk@alpha2.csd.uwm.edu (Peter J Kleczka) writes:
  13.  
  14. >Hi all
  15. >    I'm new to C programing and am trying to re-write a program
  16. >I did in pascal in C.  When I wrote the pascal program I got
  17. >caught up in the details of getting the program to work and
  18. >consequentially readability of the code and user-friendlyness
  19. >suffered......
  20.  
  21. >    The program I'm working on (below) works fine as long
  22. >as the user enters an integer.....but it gets caught in an
  23. >endless loop between the functions: firstmenu() and firstchoice()
  24. >when I enter, say, 5.5 instead of an integer
  25.  
  26. >it's unlikely that the user would enter anything but an integer
  27. >when presented with integer choices...but I want to make the
  28. >code uncrashable .....what can I do if anything to make it
  29. >so that the program doesnt do wierd things if the user enters
  30. >the wrong thing here?
  31.  
  32. Using formatted input routines like scanf() is a _very_ bad
  33. idea when dealing with user input, esp. if you have such high 
  34. ideals.
  35.  
  36. The general rule is to read a string (e.g. using fgets()) and
  37. _check_ your input while it is still a string.
  38.  
  39. >firstchoice(){ /* get users choice and branch to appropos function */
  40.  
  41. "implicit int" functions should not appear in a high qualitiy 
  42. program, because of the potential risk of an unterminated type
  43. definition that "sneaks" in just before your function definition.
  44.  
  45. >unsigned choice;
  46.  
  47. >scanf ("%d", &choice);
  48.  
  49. 1.) It is a bad idea to use a "%d" format string to read an
  50.     unsigned int. So, either change the format string to
  51.     "%u" or change the definition of choice to match the
  52.     format string.
  53.  
  54. 2.) It is a bad idea _not_ to check the return value from scanf().
  55.     If scanf() does not succeed, e.g because the first input
  56.     character happens to be a decimal dot and it is supposed
  57.     to scan an int, it will at least tell you that it did
  58.     not succed.
  59.  
  60. Kurt
  61. --
  62. | Kurt Watzka                             Phone : +49-89-2180-6254
  63. | watzka@stat.uni-muenchen.de
  64. | ua302aa@sunmail.lrz-muenchen.de
  65.  
  66.